package com.putprize.semantic.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Map;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.putprize.semantic.SemanticPoser;

public class DocumentPosProcessServlet extends HttpServlet {

    private static final long serialVersionUID = -5931056373526338377L;

    private SemanticPoser pos;
    private Gson gson = new Gson();

    public DocumentPosProcessServlet(SemanticPoser p){
        pos = p;
    }

    @Override
    protected void doGet(HttpServletRequest rq, HttpServletResponse rp)
            throws ServletException,IOException{
        process(rq,rp);
    }

    @Override
    protected void doPost(HttpServletRequest rq, HttpServletResponse rp)
            throws ServletException,IOException{
        process(rq,rp);
    }

    void process(HttpServletRequest rq, HttpServletResponse rp)
        throws ServletException,IOException {

        rq.setCharacterEncoding("UTF-8");
        rp.setCharacterEncoding("UTF-8");
        rp.setContentType("text/html");

        String data = rq.getParameter("data");

        Map<String,String> map = gson.fromJson(data, new TypeToken<Map<String,String>>() {}.getType());

        String title = "";
        if (map.containsKey("cut_title")){
            title = map.get("cut_title");
        }
        String content = "";
        if (map.containsKey("cut_content")){
            content = map.get("cut_content");
        }

        String pos_title = pos.process(title);
        String[] split_content = content.split("\n");
        StringBuilder pos_content = new StringBuilder();
        for (String line: split_content){
            pos_content.append(pos.process(line)).append("\n");
        }

        Map<String,String> res_map = new HashMap<String,String>();
        res_map.put("pos_title",pos_title);
        res_map.put("pos_content",pos_content.toString().trim());

        String res = gson.toJson(res_map);

        PrintWriter out = rp.getWriter();

        out.println(res);
    }

}
